package com.nicefact.mailmonitor.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.scribe.model.OAuthRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nicefact.mailmonitor.entity.AppUser;
import com.nicefact.mailmonitor.vo.AppProperties;

import at.tomtasche.contextio.ContextIO;

@Service
public class ContextIOService {

	@Autowired
	AppProperties appProperties;
	
	@Autowired AppUserService appUserService;

	public String syncUserMailBox(String contextIoId){
		ContextIO dokdok = new ContextIO(appProperties.getContextioKey(),
				appProperties.getContextioSecret());
		return dokdok.syncMailBox(contextIoId);
	}
	
	public String fetchMailsByUser(String userId, Date from, Date to) {
		String result = "[";
		AppUser appUser = appUserService.getUser(userId);
		if (appUser!=null && !StringUtils.isBlank(appUser.getContextioId())) {
			ContextIO dokdok = new ContextIO(appProperties.getContextioKey(),
					appProperties.getContextioSecret());
			Map<String, String> params = new HashMap<String, String>();
			int offset = 0;
			int limit = 600;
			String fromTime = "0";
			if (from != null) {
				fromTime = (from.getTime() / 1000) + "";
				params.put("date_after", fromTime);
			}
			
			if (to != null) {
				String toTime = (to.getTime() / 1000) + "";
				params.put("date_before", toTime);
			}
			//params.put("since", fromTime);
			params.put("limit", limit + "");
			String fetchedResult = "";
			long taskStart = new Date().getTime();
			long timeRunning = 0l;
			while (!fetchedResult.trim().equals("[]") && timeRunning<480) {				
				timeRunning = (new Date().getTime() - taskStart)/1000;
				System.out.println("time running for "+ userId+": " + timeRunning);
				params.put("offset", offset + "");
				fetchedResult = dokdok.fetchMails(appUser, params).trim();
				result += fetchedResult
						.substring(1, fetchedResult.length() - 1) + ",";
				offset += limit;				
				//System.out.println("fetched============== " +fetchedResult );
				if( timeRunning>=480){
					System.out.println("Stop fetching for " + userId );
				}
			}
			result = result.substring(0, result.length() - 1);
		}
		result += "]";
		return result;
	}

	public String addAccount( String mailIdToAdd,String oauthtoken,String oauthtokensecret) {
		ContextIO dokdok = new ContextIO(appProperties.getContextioKey(),
				appProperties.getContextioSecret());
	
		Map<String, String> params = new HashMap<String, String>();
		params.put("email", mailIdToAdd);
		params.put("username", mailIdToAdd);		
		params.put("server", "imap.gmail.com");		
		params.put("port", "993");
		params.put("type", "IMAP");
		params.put("service_level", "BASIC");
		params.put("usessl", "1");
		params.put("oauthtoken", oauthtoken);
		params.put("oauthtokensecret", oauthtokensecret);
		params.put("oauthconsumername", appProperties.getConsumerKey());
/*		if using api 2.0
 * 
 * dokdok.setApiVersion("2.0");			
		params.put("use_ssl", "1");
		params.put("provider_token", "1/ByFF5Dgquc25fGvJ7PqjNNCc5WIoxtfNk0N7WbfLSRs");
		params.put("provider_token_secret", "81pNorzY2EiKupsXf0SqyK5T");
		params.put("provider_consumer_key", appProperties.getConsumerKey());*/
		//params.put("", "");
		return new String(dokdok.imap_addAccount(params).getRawResponse()
				.getContent());
	}
	
	
	
}
